package com.dfy.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dfy.entity.Order;
import com.dfy.entity.Spot;
import com.dfy.mapper.OrderMapper;
import com.dfy.mapper.SpotMapper;
import com.dfy.service.OrderService;
import com.dfy.dto.OrderListRequest;
import com.dfy.dto.OrderResponse;
import com.dfy.dto.TripDTO;
import com.dfy.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;
import java.util.ArrayList;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Collections;
import java.time.LocalDate;
import org.springframework.util.StringUtils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dfy.dto.OrderRequest;
import com.dfy.dto.OrderQueryRequest;
import com.dfy.dto.OrderDTO;
import org.springframework.beans.BeanUtils;
import lombok.extern.slf4j.Slf4j;
import java.util.Objects;
import java.math.BigDecimal;

@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    private static final Logger log = LoggerFactory.getLogger(OrderServiceImpl.class);

    @Autowired
    private SpotMapper spotMapper;

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    @Transactional
    public Order createOrder(Long spotId, Long userId, OrderRequest request) {
        // 查询景点
        Spot spot = spotMapper.selectById(spotId);
        if (spot == null) {
            throw new BusinessException(404, "景点不存在");
        }

        // 计算总金额
        BigDecimal totalAmount = spot.getPrice().multiply(new BigDecimal(request.getQuantity()));

        // 创建订单
        Order order = new Order();
        order.setSpotId(spotId);
        order.setUserId(userId);
        order.setTotalAmount(totalAmount);  // 使用计算后的总金额
        order.setQuantity(request.getQuantity());
        order.setVisitDate(request.getVisitDate());
        order.setContactName(request.getContactName());
        order.setContactPhone(request.getContactPhone());
        order.setRemark(request.getRemark());
        order.setStatus("PENDING");
        order.setCreatedAt(LocalDateTime.now());
        order.setUpdatedAt(LocalDateTime.now());
        
        // 保存订单
        save(order);
        return order;
    }

    @Override
    public List<TripDTO> getUserTrips(Long userId, LocalDateTime startTime, LocalDateTime endTime) {
        // 构建查询条件
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Order::getUserId, userId)
                .ge(startTime != null, Order::getVisitDate, startTime.toString())  // 转换为字符串比较
                .le(endTime != null, Order::getVisitDate, endTime.toString())
                .orderByAsc(Order::getVisitDate);
        
        List<Order> orders = list(queryWrapper);

        // 转换为TripDTO
        return orders.stream()
            .map(order -> {
                Spot spot = spotMapper.selectById(order.getSpotId());
                if (spot == null) {
                    return null;
                }

                List<String> imageUrls = new ArrayList<>();
                try {
                    if (spot.getImageUrls() != null && !spot.getImageUrls().isEmpty()) {
                        imageUrls = Collections.singletonList(spot.getImageUrls());
                    }
                } catch (Exception e) {
                    log.error("处理景点图片URL失败: {}", e.getMessage());
                }

                return TripDTO.builder()
                    .orderId(order.getId())
                    .spotId(spot.getId())
                    .spotName(spot.getName())
                    .spotAddress(spot.getLocation())
                    .visitDate(order.getVisitDate())
                    .totalAmount(order.getTotalAmount())  // 使用 totalAmount
                    .status(order.getStatus())
                    .createdAt(order.getCreatedAt())
                    .updatedAt(order.getUpdatedAt())
                    .imageUrls(imageUrls)
                    .build();
            })
            .filter(Objects::nonNull)
            .collect(Collectors.toList());
    }

    @Override
    public List<OrderResponse> getUserOrders(Long userId, OrderListRequest request) {
        // 构建查询条件
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Order::getUserId, userId);
        
        // 根据状态筛选
        if (request.getStatus() != null && !"ALL".equals(request.getStatus())) {
            queryWrapper.eq(Order::getStatus, request.getStatus());
        }
        
        // 排序
        if (request.getSortField() != null) {
            if ("price".equals(request.getSortField())) {
                // 使用 totalAmount 替代 price
                if ("desc".equalsIgnoreCase(request.getSortOrder())) {
                    queryWrapper.orderByDesc(Order::getTotalAmount);
                } else {
                    queryWrapper.orderByAsc(Order::getTotalAmount);
                }
            } else if ("createdAt".equals(request.getSortField())) {
                if ("desc".equalsIgnoreCase(request.getSortOrder())) {
                    queryWrapper.orderByDesc(Order::getCreatedAt);
                } else {
                    queryWrapper.orderByAsc(Order::getCreatedAt);
                }
            }
        } else {
            queryWrapper.orderByDesc(Order::getCreatedAt);  // 默认按创建时间倒序
        }
        
        // 执行查询
        List<Order> orders = list(queryWrapper);
        
        // 转换为 OrderResponse
        return orders.stream()
            .map(this::convertToOrderResponse)
            .filter(Objects::nonNull)
            .collect(Collectors.toList());
    }

    @Override
    public OrderResponse getOrder(Long orderId) {
        // 获取订单信息
        Order order = getById(orderId);
        if (order == null) {
            throw new BusinessException(404, "订单不存在");
        }

        // 获取景点信息
        Spot spot = spotMapper.selectById(order.getSpotId());
        if (spot == null) {
            throw new BusinessException(404, "订单关联的景点不存在");
        }

        // 处理图片URL
        List<String> imageUrls = new ArrayList<>();
        try {
            if (spot.getImageUrls() != null && !spot.getImageUrls().isEmpty()) {
                if (spot.getImageUrls().startsWith("[")) {
                    imageUrls = objectMapper.readValue(
                        spot.getImageUrls(), 
                        new TypeReference<List<String>>() {}
                    );
                } else {
                    imageUrls = Collections.singletonList(spot.getImageUrls());
                }
            }
        } catch (Exception e) {
            log.error("处理景点图片URL失败: {}", e.getMessage());
        }

        return OrderResponse.builder()
            .orderId(order.getId())
            .userId(order.getUserId())
            .spotId(spot.getId())
            .spotName(spot.getName())
            .totalAmount(order.getTotalAmount())  // 使用 totalAmount 替代 price
            .quantity(order.getQuantity())
            .contactName(order.getContactName())
            .contactPhone(order.getContactPhone())
            .remark(order.getRemark())
            .status(order.getStatus())
            .createdAt(order.getCreatedAt())
            .updatedAt(order.getUpdatedAt())
            .imageUrls(imageUrls)
            .build();
    }

    @Override
    @Transactional
    public void cancelOrder(Long orderId, Long userId) {
        // 获取订单信息
        Order order = getById(orderId);
        if (order == null) {
            throw new BusinessException(404, "订单不存在");
        }

        // 验证订单所属
        if (!order.getUserId().equals(userId)) {
            throw new BusinessException(403, "无权操作此订单");
        }

        // 检查订单状态
        if ("CANCELLED".equals(order.getStatus())) {
            throw new BusinessException(400, "订单已取消");
        }
        if ("COMPLETED".equals(order.getStatus())) {
            throw new BusinessException(400, "已完成的订单不能取消");
        }

        // 更新订单状态
        order.setStatus("CANCELLED");
        order.setUpdatedAt(LocalDateTime.now());
        
        // 保存更新
        if (!updateById(order)) {
            throw new BusinessException(500, "取消订单失败");
        }
    }

    @Override
    public List<OrderResponse> getAllOrders(OrderListRequest request) {
        // 构建查询条件
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
        
        // 根据状态筛选
        if (request.getStatus() != null && !"ALL".equals(request.getStatus())) {
            queryWrapper.eq(Order::getStatus, request.getStatus());
        }
        
        // 排序
        if (request.getSortField() != null) {
            switch (request.getSortField()) {
                case "totalAmount":
                    queryWrapper.orderBy(true, "desc".equalsIgnoreCase(request.getSortOrder()), 
                                  Order::getTotalAmount);
                    break;
                case "createdAt":
                    queryWrapper.orderBy(true, "desc".equalsIgnoreCase(request.getSortOrder()), 
                                  Order::getCreatedAt);
                    break;
                default:
                    queryWrapper.orderByDesc(Order::getCreatedAt);
            }
        } else {
            queryWrapper.orderByDesc(Order::getCreatedAt);
        }
        
        // 执行查询
        List<Order> orders = list(queryWrapper);
        
        // 转换为 OrderResponse
        return orders.stream()
            .map(this::convertToOrderResponse)
            .filter(Objects::nonNull)
            .collect(Collectors.toList());
    }

    @Override
    @Transactional
    public void confirmOrder(Long order_id) {
        // 获取订单信息
        Order order = getById(order_id);
        if (order == null) {
            throw new BusinessException(404, "订单不存在");
        }

        // 检查订单状态
        if ("CANCELLED".equals(order.getStatus())) {
            throw new BusinessException(400, "已取消的订单不能确认");
        }
        if ("COMPLETED".equals(order.getStatus())) {
            throw new BusinessException(400, "订单已经确认");
        }

        // 更新订单状态
        order.setStatus("COMPLETED");
        order.setUpdatedAt(LocalDateTime.now());
        
        // 保存更新
        if (!updateById(order)) {
            throw new BusinessException(500, "确认订单失败");
        }
    }

    @Override
    @Transactional
    public void adminCancelOrder(Long orderId, String reason) {
        // 获取订单信息
        Order order = getById(orderId);
        if (order == null) {
            throw new BusinessException(404, "订单不存在");
        }

        // 检查订单状态
        if ("CANCELLED".equals(order.getStatus())) {
            throw new BusinessException(400, "订单已经取消");
        }
        if ("COMPLETED".equals(order.getStatus())) {
            throw new BusinessException(400, "已完成的订单不能取消");
        }

        // 更新订单状态
        order.setStatus("CANCELLED");
        order.setUpdatedAt(LocalDateTime.now());
        // 如果 Order 实体中有 cancelReason 字段，则设置取消原因
        // order.setCancelReason(reason);
        
        // 保存更新
        if (!updateById(order)) {
            throw new BusinessException(500, "取消订单失败");
        }
        
        log.info("管理员取消订单成功，订单ID：{}，取消原因：{}", orderId, reason);
    }

    @Override
    public Page<OrderResponse> getOrderPage(OrderListRequest request) {
        log.info("开始查询订单列表 - 请求参数: {}", request);
        
        // 创建分页对象
        Page<Order> page = new Page<>(request.getPageNum(), request.getPageSize());
        
        // 构建查询条件
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        
        // 只有在userId不为null时才添加用户ID条件
        if (request.getUserId() != null) {
            wrapper.eq(Order::getUserId, request.getUserId());
        }
        
        // 状态条件，如果不是ALL才添加状态条件
        if (StringUtils.hasText(request.getStatus()) && !"ALL".equals(request.getStatus())) {
            wrapper.eq(Order::getStatus, request.getStatus());
        }
        
        // 关键字搜索
        if (StringUtils.hasText(request.getKeyword())) {
            wrapper.and(w -> w
                .like(Order::getContactName, request.getKeyword())
                .or()
                .like(Order::getContactPhone, request.getKeyword())
                .or()
                .like(Order::getRemark, request.getKeyword())
            );
        }
        
        // 排序
        if (StringUtils.hasText(request.getSortField())) {
            boolean isAsc = "ascend".equals(request.getSortOrder());
            switch (request.getSortField()) {
                case "totalAmount":
                    wrapper.orderBy(true, isAsc, Order::getTotalAmount);
                    break;
                case "createdAt":
                    wrapper.orderBy(true, isAsc, Order::getCreatedAt);
                    break;
                case "visitDate":
                    wrapper.orderBy(true, isAsc, Order::getVisitDate);
                    break;
                default:
                    wrapper.orderByDesc(Order::getCreatedAt);
            }
        } else {
            wrapper.orderByDesc(Order::getCreatedAt);
        }
        
        // 执行分页查询
        Page<Order> orderPage = page(page, wrapper);
        log.info("查询到订单数量: {}", orderPage.getTotal());
        
        // 转换为 OrderResponse
        return convertToOrderResponsePage(orderPage);
    }

    // 添加辅助方法用于转换分页结果
    private Page<OrderResponse> convertToOrderResponsePage(Page<Order> orderPage) {
        Page<OrderResponse> responsePage = new Page<>(
            orderPage.getCurrent(),
            orderPage.getSize(),
            orderPage.getTotal()
        );
        
        if (orderPage.getRecords() != null) {
            List<OrderResponse> responseList = orderPage.getRecords().stream()
                .map(this::convertToOrderResponse)
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
            responsePage.setRecords(responseList);
        }
        log.info("转换后的订单数据: {}", responsePage.getRecords());
        return responsePage;
    }

    // 修改转换方法
    private OrderResponse convertToOrderResponse(Order order) {
        Spot spot = spotMapper.selectById(order.getSpotId());
        if (spot == null) {
            return null;
        }

        List<String> imageUrls = new ArrayList<>();
        try {
            if (spot.getImageUrls() != null && !spot.getImageUrls().isEmpty()) {
                if (spot.getImageUrls().startsWith("[")) {
                    imageUrls = objectMapper.readValue(
                        spot.getImageUrls(), 
                        new TypeReference<List<String>>() {}
                    );
                } else {
                    imageUrls = Collections.singletonList(spot.getImageUrls());
                }
            }
        } catch (Exception e) {
            log.error("处理景点图片URL失败: {}", e.getMessage());
        }

        return OrderResponse.builder()
            .orderId(order.getId())
            .userId(order.getUserId())
            .spotId(spot.getId())
            .spotName(spot.getName())
            .totalAmount(order.getTotalAmount())
            .quantity(order.getQuantity())
            .contactName(order.getContactName())
            .contactPhone(order.getContactPhone())
            .remark(order.getRemark())
            .status(order.getStatus())
            .visitDate(order.getVisitDate())
            .createdAt(order.getCreatedAt())
            .updatedAt(order.getUpdatedAt())
            .imageUrls(imageUrls)
            .build();
    }

    public OrderDTO getOrderDetail(Long orderId) {
        Order order = getById(orderId);
        if (order == null) {
            throw new BusinessException(404, "订单不存在");
        }
        
        // 获取景点信息
        Spot spot = spotMapper.selectById(order.getSpotId());
        if (spot == null) {
            throw new BusinessException(404, "景点信息不存在");
        }
        
        OrderDTO orderDTO = new OrderDTO();
        BeanUtils.copyProperties(order, orderDTO);
        orderDTO.setSpotName(spot.getName());
        orderDTO.setSpotAddress(spot.getLocation());
        
        return orderDTO;
    }
    
    public Page<Order> getOrderList(OrderQueryRequest request) {
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
        
        // 添加查询条件
        if (request.getUserId() != null) {
            queryWrapper.eq(Order::getUserId, request.getUserId());
        }
        if (StringUtils.hasText(request.getStatus())) {
            queryWrapper.eq(Order::getStatus, request.getStatus());
        }
        
        // 添加排序
        if (request.getSortField() != null) {
            switch (request.getSortField()) {
                case "totalAmount":
                    queryWrapper.orderBy(true, request.isAscending(), Order::getTotalAmount);
                    break;
                case "createdAt":
                    queryWrapper.orderBy(true, request.isAscending(), Order::getCreatedAt);
                    break;
                default:
                    queryWrapper.orderByDesc(Order::getCreatedAt);
            }
        } else {
            queryWrapper.orderByDesc(Order::getCreatedAt);
        }
        
        return page(new Page<>(request.getPage(), request.getSize()), queryWrapper);
    }

    @Override
    public Page<OrderDTO> getMyOrders(Long userId, String status, Integer current, Integer size) {
        log.info("开始查询用户订单 - userId: {}, status: {}", userId, status);
        
        // 使用 Wrapper 查询
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Order::getUserId, userId)
              .eq(!"ALL".equals(status), Order::getStatus, status)
              .orderByDesc(Order::getCreatedAt);
        
        // 使用 MyBatis-Plus 的分页查询
        Page<Order> orderPage = page(new Page<>(current, size), wrapper);
        
        // 转换为 DTO
        Page<OrderDTO> dtoPage = new Page<>();
        BeanUtils.copyProperties(orderPage, dtoPage, "records");
        
        List<OrderDTO> dtoList = orderPage.getRecords().stream()
            .map(order -> {
                OrderDTO dto = new OrderDTO();
                BeanUtils.copyProperties(order, dto);
                
                // 获取景点名称和地址
                Spot spot = spotMapper.selectById(order.getSpotId());
                if (spot != null) {
                    dto.setSpotName(spot.getName());
                    dto.setSpotAddress(spot.getLocation());
                }
                
                return dto;
            })
            .collect(Collectors.toList());
        
        dtoPage.setRecords(dtoList);
        log.info("查询结果 - 总数: {}, 当前页数据: {}", dtoPage.getTotal(), dtoPage.getRecords());
        
        return dtoPage;
    }
} 